package com.alpha.common.utils;

import java.security.SecureRandom;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串工具类
 * @author zhaojiulin
 * @date 2020/2/27 13:34
 */
public class StrUtils {

    /**
     * 字符串内容字段替换
     * @param content 字符串
     * @param map 数据map
     * @return 字符串
     */
    public String replaceParam(String content, Map map) {
        String param = "";
        for (Object key : map.keySet()) {
            param = "" + key.toString() + "";
            if (content.indexOf(param) > -1)
                content = content.replaceAll(param, map.get(key.toString()).toString());
        }
        content = content.replaceAll("date", DateTimeUtil.nowDateTimeStr1());
        return content;
    }

    /**
     * 去除字符串 空格 、回车等
     * @param str
     * @return
     */
    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    private static final Random RANDOM = new SecureRandom();


    public static String generateNonceStr() {
        return generateNonceStr(32);
    }

    public static String generateNonceStr(int len) {
        return generateNonceStr("", len);
    }
    public static String generateNonceStr(String prefix, int len) {
        char[] nonceChars = new char[len];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return prefix + new String(nonceChars);
    }
}
